package cn.stylefeng.guns.sys.modular.system.service;

import cn.stylefeng.guns.sys.core.util.MessageType;
import cn.stylefeng.guns.sys.core.util.TextMessage;
import cn.stylefeng.guns.sys.core.util.XmlUtil;
import cn.stylefeng.guns.sys.modular.system.entity.BtyWx;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWxMapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 处理接收信息和回复消息的服务类接口
 *
 * @author Administrator
 *
 */
@Service
public class WebChatService {
    private Logger logger = LoggerFactory.getLogger(WebChatService.class);
    @Resource
    private DictService dictService;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private UserService userService;

    // 处理微信发来的请求 map 消息业务处理分发
    public  String parseMessage(Map<String, String> map,String msgText) {

        String respXml = null;
        try {
            // 发送方帐号
            String fromUserName = map.get("FromUserName");
            // 开发者微信号
            String toUserName = map.get("ToUserName");
            // 取得消息类型
            String MsgType = map.get("MsgType");
            // 发现直接把要返回的信息直接封装成replyMap集合，然后转换成 xml文件，是不是实体类可以不用了
            Map<String, String> replyMap = new HashMap<String, String>();
            replyMap.put("ToUserName", fromUserName);
            replyMap.put("FromUserName", toUserName);
            replyMap.put("CreateTime", String.valueOf(System.currentTimeMillis()));

            if (MsgType.equals(MessageType.TEXT_MESSAGE)) {
                // 封装文本返回消息
                TextMessage textMessage = new TextMessage();
                textMessage.setToUserName(fromUserName);
                textMessage.setFromUserName(toUserName);
                textMessage.setCreateTime(System.currentTimeMillis());
                textMessage.setContent("您发送的是文本消息");
                textMessage.getMsgType();
                // respXml = ReplyMessageUtil.sendTextMessage(textMessage);

                // 用map集合封装
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                //replyMap.put("Content", "文本消息");

                replyMap.put("Content", msgText);
                respXml = XmlUtil.xmlFormat(replyMap, true);
                System.out.println("respXml:"+respXml);
            }
//            else if (MsgType.equals(MessageType.IMAGE_MESSAGE)) {
//                // 这里回复图片 或者图文消息 以图文消息为例
//                NewsOutputMessage message = new NewsOutputMessage();
//                message.setToUserName(fromUserName);
//                message.setFromUserName(toUserName);
//                message.setCreateTime(new Date().getTime());
//                message.getMsgType();
//
//                Articles article = new Articles();
//                article.setDescription("图文消息 "); // 图文消息的描述
//                article.setPicUrl("https://p4.ssl.cdn.btime.com/dmfd/192_108_/t019d0b65e33000f8a0.jpg?size=458x240"); // 图文消息图片地址
//                article.setTitle("图文消息 "); // 图文消息标题
//                article.setUrl("http://www.baidu.com"); // 图文 url 链接
//                List<Articles> list = new ArrayList<Articles>();
//                list.add(article);// 这里发送的是单图文，如果需要发送多图文则在这里 list 中加入多个
//                // Articles！
//
//                message.setArticleCount(list.size());
//                message.setArticles(list);
//                respXml = ReplyMessageUtil.sendImageTextMessage(message);
//            }
            else if (MsgType.equals(MessageType.VOICE_MESSAGE)) {
                // 以下方式根据需要来操作
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                replyMap.put("Content", "您发送的是语音消息");
                respXml = XmlUtil.xmlFormat(replyMap, true);
            } else if (MsgType.equals(MessageType.VIDEO_MESSAGE)) {
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                replyMap.put("Content", "您发送的是视频消息");
                respXml = XmlUtil.xmlFormat(replyMap, true);
            } else if (MsgType.equals(MessageType.SHORTVIDEO_MESSAGE)) {
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                replyMap.put("Content", "您发送的是小视频消息");
                respXml = XmlUtil.xmlFormat(replyMap, true);
            } else if (MsgType.equals(MessageType.POSOTION_MESSAGE)) {
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                replyMap.put("Content", "您发送的是地理位置消息");
                respXml = XmlUtil.xmlFormat(replyMap, true);
            } else if (MsgType.equals(MessageType.LINK_MESSAGE)) {
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                replyMap.put("Content", "您发送的是链接消息");
                respXml = XmlUtil.xmlFormat(replyMap, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respXml;
    }

    // 事件消息业务分发
    public  String parseEvent(Map<String, String> map) {
        String respXml = null;
        try {
            // 发送方帐号
            String fromUserName = map.get("FromUserName");
            // 开发者微信号
            String toUserName = map.get("ToUserName");
            // 取得消息类型
            String MsgType = map.get("MsgType");
            //获取事件类型
            String eventType = map.get("Event");
            logger.info("eventType:"+eventType);
            //获取点击事件的key值
            String eventKey = map.get("EventKey")==null?"":map.get("EventKey");

            // 发现直接把要返回的信息直接封装成replyMap集合，然后转换成 xml文件，是不是实体类可以不用了
            Map<String, String> replyMap = new HashMap<String, String>();
            replyMap.put("ToUserName", fromUserName);
            replyMap.put("FromUserName", toUserName);
            replyMap.put("CreateTime", String.valueOf(System.currentTimeMillis()));
            if (eventType.equals(MessageType.EVENT_TYPE_SUBSCRIBE)) {//关注
                // 用map集合封装
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                //replyMap.put("Content", MessageType.menuText());
                replyMap.put("Content", "您好,欢迎关注半天妖青花椒烤鱼!\r\n" +
                        "【1】供货商请输入 姓名#银行卡号绑定! 例如：张三#621700233\r\n" +
                        "【2】绑定易快报请输入 姓名*银行卡号！例如：李四*621700234000\r\n" +
                        "【3】绑定部门或职级请输入 姓名@电话@部门或职级 例如：王五@158533@财务部   张三@15965512345@督导");

            String openid = map.get("FromUserName");
            Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
            String accessToken = "";
            if (ToolUtil.isNotEmpty(dict)) {
                accessToken = dict.getName();
            }
            //通过openid获取昵称
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
            //String url = "https://api.weixin.qq.com/cgi-bin/user/info";
            String userInfo = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(userInfo);
            if(ToolUtil.isNotEmpty(jsonObject)){
               String nickName = jsonObject.get("nickname")==null?"":jsonObject.get("nickname").toString();
               String unionid=jsonObject.get("unionid")==null?"":jsonObject.get("unionid").toString();
               //保存openid和微信昵称
               BtyWx btyWx1=btyWxMapper.selectOne(new QueryWrapper<BtyWx>().eq("openid",openid));
               if(ToolUtil.isEmpty(btyWx1)){
                   BtyWx btyWx=new BtyWx();
                   btyWx.setOpenid(openid);
                   btyWx.setNickname(nickName);
                   btyWx.setUnionid(unionid);
                   btyWxMapper.insert(btyWx);
               }else{
                   String nickname=btyWx1.getNickname();
                  // if(!nickname.equals(nickName)){
                   btyWx1.setNickname(nickName);
                   btyWx1.setUnionid(unionid);
                   btyWxMapper.updateById(btyWx1);
                  // }
               }
            }
                respXml = XmlUtil.xmlFormat(replyMap, true);
            }
            if (eventType.equals(MessageType.EVENT_TYPE_UNSUBSCRIBE)) {// 取消关注
                replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                replyMap.put("Content", "欢迎下次关注!");
                respXml = XmlUtil.xmlFormat(replyMap, true);
            }
            if (eventType.equals(MessageType.EVENT_TYPE_SCAN)) {// 用户已关注时的扫描带参数二维码

            }
            if (eventType.equals(MessageType.EVENT_TYPE_LOCATION)) {// 上报地理位置

            }
            if (eventType.equals(MessageType.EVENT_TYPE_CLICK)) {// 自定义菜单
               if(eventKey.equals("weihudong")){
                   replyMap.put("MsgType", MessageType.RESP_MESSAGE_TYPE_TEXT);
                   replyMap.put("Content", "同学,我们可以互动一下吗?");
                   respXml = XmlUtil.xmlFormat(replyMap, true);

               }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respXml;
    }
}